package com.psp.web.service.impl;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.northend.util.AppTextUtil;
import com.northend.util.DateUtil;
import com.northend.util.MD5Util;
import com.northend.util.NumUtil;
import com.northend.util.RandomUtil;
import com.northend.util.StringUtil;
import com.northend.util.VCodeSender;
import com.psp.web.cache.dao.UserCacheDao;
import com.psp.web.constants.StringConstants;
import com.psp.web.model.Code;
import com.psp.web.model.UserBean;
import com.psp.web.model.UserLoginLogBean;
import com.psp.web.model.UserUpdateLogBean;
import com.psp.web.netease.NeteaseManager;
import com.psp.web.persist.dao.UserDao;
import com.psp.web.service.UserService;
import com.psp.web.service.exception.ServiceException;
import com.psp.web.util.MailSendUtil;

@Service
public class UserServiceImpl implements UserService {
	Logger logger = Logger.getLogger(UserServiceImpl.class);
	@Autowired
	UserDao userImpl;
	@Autowired
	UserCacheDao userCacheImpl;

	VCodeSender phoneCode = VCodeSender.getInstance("N1330628", "t7NYh90uB");

	@Autowired
	NeteaseManager neteaseManager;

	public static void main(String[] args) {
		VCodeSender phoneCode = VCodeSender.getInstance("N1330628", "t7NYh90uB");
		String msg = StringConstants.getInstance().getString("msg_vcode_send", new Object[] { "1234", 5 });
		phoneCode.send("17610075502", msg, null);
	}

	/**
	 * 通过电话注册
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public UserBean regByPhone(String sessionId, String phone, String pwd, String confirmPwd, String vcode,
			String device, String ip) {
		Code code = userCacheImpl.getVCode(1, phone);
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}
		logger.info("phone is:" + phone + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}
		UserBean user = userImpl.selectOneByPhone(phone);
		if (user != null) {
			throw new ServiceException("object_is_exist", new Object[] { "用户" });
		}
		if (!pwd.equals(confirmPwd)) {
			throw new ServiceException("user_password_is_not_same");
		}
		UserBean newuser = new UserBean();
		newuser.setUid(AppTextUtil.getPrimaryKey());
		newuser.setNickName("未命名" + phone.substring(6, phone.length()));
		newuser.setHeadIcon("http://os4z3g2v6.bkt.clouddn.com/Fm4aPTrJFVacoz0E0xhdIGMWcwwD");// 默认头像
		newuser.setGender(1);// 默认男
		newuser.setPhone(phone);
		newuser.setPassword(MD5Util.sha256Hex(pwd));
		newuser.setDevice(device);
		newuser.setState(Integer.valueOf(1));

		boolean flag = userImpl.insert(newuser) > 0;

		logger.info("new User is:" + newuser);
		if (flag) {
			userCacheImpl.setUserSession(sessionId, newuser.getUid(), 86400L);

			// TODO 创建网易云信账号 并且添加七个业务组
			neteaseManager.create(newuser.getUid(), newuser.getNickName(), null, null, sessionId);
			neteaseManager.addFriend("serviceCategory1", newuser.getUid(), 1, null);
			neteaseManager.addFriend("serviceCategory2", newuser.getUid(), 1, null);
			neteaseManager.addFriend("serviceCategory3", newuser.getUid(), 1, null);
			neteaseManager.addFriend("serviceCategory4", newuser.getUid(), 1, null);
			neteaseManager.addFriend("serviceCategory5", newuser.getUid(), 1, null);
			neteaseManager.addFriend("serviceCategory6", newuser.getUid(), 1, null);
			neteaseManager.addFriend("serviceCategory7", newuser.getUid(), 1, null);

			UserLoginLogBean loginLog = new UserLoginLogBean();
			loginLog.setDevice(device);
			loginLog.setLoginIp(ip);
			loginLog.setUid(newuser.getUid());
			loginLog.setOstate(2);// 1 登录 2注册
			flag = userImpl.insertLoginLog(loginLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return newuser;
	}

	/**
	 * 通过邮箱注册
	 */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public UserBean regByEmail(String sessionId, String email, String pwd, String confirmPwd, String device,
			String ip) {
		UserBean user = userImpl.selectOneByEmail(email);
		if (user != null) {
			throw new ServiceException("object_is_exist", new Object[] { "用户" });
		}
		if (!pwd.equals(confirmPwd)) {
			throw new ServiceException("user_password_is_not_same");
		}
		UserBean newuser = new UserBean();
		newuser.setUid(AppTextUtil.getPrimaryKey());
		newuser.setEmail(email);
		newuser.setHeadIcon("http://os4z3g2v6.bkt.clouddn.com/Fm4aPTrJFVacoz0E0xhdIGMWcwwD");// 默认头像
		newuser.setNickName("未命名" + email.substring(0, 5));
		newuser.setGender(1);// 默认男
		newuser.setPassword(MD5Util.sha256Hex(pwd));
		newuser.setDevice(device);
		newuser.setState(Integer.valueOf(2));// 邮箱待激活

		boolean flag = userImpl.insert(newuser) > 0;

		logger.info("new User is:" + newuser);
		if (flag) {
			userCacheImpl.setUserSession(sessionId, newuser.getUid(), 86400L);
			neteaseManager.create(newuser.getUid(), newuser.getNickName(), null, null, sessionId); // TODO 创建网易云信账号
			UserLoginLogBean loginLog = new UserLoginLogBean();
			loginLog.setDevice(device);
			loginLog.setLoginIp(ip);
			loginLog.setUid(newuser.getUid());
			loginLog.setOstate(2);// 1 登录 2注册
			flag = userImpl.insertLoginLog(loginLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return newuser;
	}

	@Override
	public UserBean existUser(int type, String username) {
		UserBean user = null;
		if (StringUtil.isMobileNO(username)) {
			user = userImpl.selectOneByPhone(username);
		} else if (StringUtil.isEmail(username)) {
			user = userImpl.selectOneByEmail(username);
		}
		if (type == 1) {
			if (user == null) {
				throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
			}
		} else if ((type == 2) && (user != null)) {
			throw new ServiceException("object_is_exist", new Object[] { "用户" });
		}
		return user;
	}

	@Override
	public UserBean existUser(String sessionId) {
		String uid = userCacheImpl.getUidBySession(sessionId);
		if (uid == null) {
			return null;
		}
		return userImpl.selectOne(uid);
	}

	@Override
	public boolean sendVCode(int type, String phone) {
		UserBean user = userImpl.selectOneByPhone(phone);
		if ((type == 1 | type == 4) && user != null) {// 1 绑定手机号，2 更新手机号,3 找回密码
			throw new ServiceException("object_is_exist", new Object[] { "手机号" });
		} else if (type == 2 | type == 3) {
			if (user == null)
				throw new ServiceException("object_is_not_exist", new Object[] { "手机号" });
		}
		long now = System.currentTimeMillis() / 1000;
		logger.info("now is : " + now);

		Code c = userCacheImpl.getVCode(type, phone);
		logger.info("vcode is : " + c);
		if (c != null) {
			long passTime = now - c.getTime();
			logger.info("passTime is : " + passTime);
			if (passTime < 60) {
				throw new ServiceException("vcode_in_limit");
			}
		}
		String vcode = RandomUtil.getRandomNum(4);
		logger.info("the phone vcode is : " + vcode);
		Code cacheCode = new Code();
		cacheCode.setCode(vcode);
		cacheCode.setTime(System.currentTimeMillis() / 1000);
		userCacheImpl.setVCode(type, phone, cacheCode);

		String msg = StringConstants.getInstance().getString("msg_vcode_send", new Object[] { vcode, 5 });
		phoneCode.send(phone, msg, null);
		return true;
	}

	@Override
	public void checkImgCode(String userName, String i) {
		Code imgCode = userCacheImpl.getImgCode(userName);
		logger.info("the imgcode is : " + imgCode);
		if (imgCode == null) {
			throw new ServiceException("imgcode_is_expire");
		}
		i = i.toUpperCase();
		if ((StringUtil.isEmpty(i)) || (!i.equals(imgCode.getCode()))) {
			logger.info("set imgcode is : " + imgCode);
			throw new ServiceException("imgcode_is_error");
		}
	}

	@Override
	public boolean sendActivateEmail(String email) {
		if (!StringUtil.isEmail(email)) {
			throw new ServiceException("param_is_error", new Object[] { "邮箱" });
		}
		UserBean user = userImpl.selectActiveUserByEmail(email);
		if (user == null) {
			throw new ServiceException("user_is_not_register");
		}
		String verifyCode = userCacheImpl.getEmailCodeByUid(user.getUid());
		if (verifyCode == null) {
			verifyCode = AppTextUtil.getFileKey();
		}
		StringBuffer emailbuffer = new StringBuffer();
		emailbuffer.append(
				"<table style='border-collapse: collapse; border-spacing: 0; font: 18px/34px 'Microsoft Yahei', Tahoma; text-align: left;'>");
		emailbuffer.append(
				"<thead>\t\t\t<tr style='border-bottom: 1px solid #ccc;'>\t\t\t\t<th style='padding: 10px 40px;' align='left'>");
		emailbuffer.append(
				"<img src=\"http://fwpt.zpark-imway.com/psp-user/dcef89f338e3445e0ff07a799038edeb.png\" alt=\"公共服务平台\" title=\"公共服务平台\"></th></tr></thead>\t");
		emailbuffer.append(
				"<tbody><tr><td style=\"padding: 0 40px;\"><p style=\"margin-top: 20px;\"亲爱的用户：<br> 您好！<br> 您于");
		String now = DateUtil.getDate(null);
		emailbuffer.append(now + "申请注册公共服务平台账号" + email + "<br>");
		emailbuffer.append("点击下方激活链接即可完成注册：</p>");
		emailbuffer.append("<p style=\"line-height: 28px; margin-top: 30px;\"><a href=\""
				+ "http://fwpt.zpark-imway.com/psp-user/#/activeEmail/" + verifyCode
				+ "\" target=\"_blank\" style=\"text-decoration: underline; color: #39c;\">");
		emailbuffer.append("http://fwpt.zpark-imway.com/psp-user/#/activeEmail/" + verifyCode + "</a></p>");
		emailbuffer.append("<span style=\"font-size: 12px; color: #999;\">如果您无法点击此链接，请将它复制到浏览器地址栏后访问</span>");
		emailbuffer.append("<p style=\"line-height: 25px; font-size: 14px; margin-top: 20px;\">");
		emailbuffer.append("1.为了保障您账号的安全性，请在24小时内完成激活，此链接将在您激活过一次后失效！<br>");
		emailbuffer.append("2.请尽快完成激活，否则链接将过期，中关村公共服务平台将有权于24小时后收回账号；<br>");
		emailbuffer.append("3.本邮件由中关村公共服务平台官网系统自动发出，请勿直接回复！<br>");
		emailbuffer.append("4.如果您有任何疑问或建议，请随时拨打中关村公共服务平台客服热线：400-888-1111</p></p></td></tr>\t</tbody></table><br><br>");
		String theme = "您已创建公共服务平台账号，请激活";
		boolean flag = MailSendUtil.sendMail(email, theme, emailbuffer.toString());
		if (flag) {
			userCacheImpl.setEmailCode(user.getUid(), verifyCode);
			return flag;
		}
		return false;
	}

	@Override
	public boolean activateEmail(String code) {
		String userId = userCacheImpl.getUidByEmailCode(code);
		if (userId == null) {
			throw new ServiceException("vcode_is_expire");
		}
		UserBean user = userImpl.selectOne(userId);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		int state = user.getState().intValue();
		if (state == 1) {
			throw new ServiceException("user_is_actived");
		}

		boolean flag = userImpl.updateState(userId, 1) > 0;
		if (flag) {
			UserUpdateLogBean updateLog = new UserUpdateLogBean();
			updateLog.setUid(userId);
			updateLog.setOldData("状态：2，邮箱注册待激活");
			updateLog.setData("状态：1已激活");
			updateLog.setOstate(1);
			flag = userImpl.insertUpdateLog(updateLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return userImpl.updateState(userId, 1) > 0;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public UserBean login(String sessionId, String userName, String pwd, String vcode, String device, String ip) {

		UserBean user = null;
		if (StringUtil.isMobileNO(userName)) {
			user = userImpl.selectOneByPhone(userName);
		} else if (StringUtil.isEmail(userName)) {
			user = userImpl.selectOneByEmail(userName);
		}
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		Code code = userCacheImpl.getLoginCode(user.getUid());
		if (code == null) {
			code = new Code();
			code.setNum(0);
			userCacheImpl.setLoginCode(user.getUid(), code);
		} else if (code.getNum() > 4) {
			if (StringUtil.isEmpty(code.getCode())) {
				throw new ServiceException("imgcode_is_cross");
			}
			if (!code.getCode().equals(vcode.toUpperCase())) {
				throw new ServiceException("imgcode_is_error");
			}
		}

		pwd = MD5Util.sha256Hex(pwd);
		if (!pwd.equals(user.getPassword())) {
			code.setNum(code.getNum() + 1);
			userCacheImpl.setLoginCode(user.getUid(), code);
			throw new ServiceException("user_password_is_error");
		}

		if (NumUtil.toInt(user.getState(), 0) == 2) {
			throw new ServiceException("user_is_not_active");
		}

		userCacheImpl.setUserSession(sessionId, user.getUid(), 86400L);
		boolean flag = userImpl.updateLoginTime(user.getUid()) > 0;
		if (flag) {
			logger.info("sessionId= " + sessionId);
			// neteaseManager.update(user.getUid(), null, sessionId); // TODO 更新网易云信账户
			UserLoginLogBean loginLog = new UserLoginLogBean();
			loginLog.setDevice(device);
			loginLog.setLoginIp(ip);
			loginLog.setUid(user.getUid());
			loginLog.setOstate(1);// 1 登录 2注册
			flag = userImpl.insertLoginLog(loginLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}

		return user;
	}

	@Override
	public UserBean getUser(String userId) {
		return userImpl.selectOne(userId);
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public UserBean updateUser(String userId, String content, int type) {
		UserBean user = userImpl.selectOne(userId);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		String oldData = null;
		// 1姓名2头像，3身份证，4性别
		switch (type) {
		case 1:
			oldData = "昵称：" + user.getNickName();
			user.setNickName(content);
			break;
		case 2:
			oldData = "头像：" + user.getHeadIcon();
			user.setHeadIcon(content);
			break;
		case 3:
			oldData = "身份证：" + user.getIdno();
			user.setIdno(content);
			break;
		case 4:
			oldData = "性别：" + user.getGender();
			user.setGender(NumUtil.toInt(content, 1));// 默认设置男
			break;
		default:
			break;
		}
		boolean flag = userImpl.updateUser(user) > 0;
		if (flag) {
			UserUpdateLogBean updateLog = new UserUpdateLogBean();
			updateLog.setUid(userId);
			updateLog.setOldData(oldData);
			updateLog.setData(content);
			updateLog.setOstate(1);
			flag = userImpl.insertUpdateLog(updateLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return user;
	}

	@Override
	public UserBean sendFindPwdCode(String userName, String code, String key) {
		UserBean user = userImpl.selectOneByPhone(userName);
		if (user == null)
			throw new ServiceException("object_is_not_exist", new Object[] { "未注册，手机号" });
		checkImgCode(key, code);
		String vcode = RandomUtil.getRandomNum(4);
		logger.info("the phone vcode is : " + vcode);
		Code cacheCode = new Code();
		cacheCode.setCode(vcode);
		cacheCode.setTime(System.currentTimeMillis() / 1000);

		// userCacheImpl.setVCode(3, userName, cacheCode);
		boolean flag = false;
		if (StringUtil.isMobileNO(userName)) {// 手机发送短信验证码
			String msg = StringConstants.getInstance().getString("msg_vcode_send", new Object[] { vcode, 5 });
			flag = phoneCode.send(userName, msg, null);

		} else if (StringUtil.isEmail(userName)) {
			StringBuffer emailbuffer = new StringBuffer();
			emailbuffer.append(
					"<table style='border-collapse: collapse; border-spacing: 0; font: 18px/34px 'Microsoft Yahei', Tahoma; text-align: left;'>");
			emailbuffer.append(
					"<thead>\t\t\t<tr style='border-bottom: 1px solid #ccc;'>\t\t\t\t<th style='padding: 10px 40px;' align='left'>");
			emailbuffer.append(
					"<img src=\"http://47.93.144.246/psp-web/img/logo-oneplus.png\" alt=\"公共服务平台\"></th></tr></thead>\t");
			emailbuffer.append(
					"<tbody><tr><td style=\"padding: 0 40px;\"><p style=\"margin-top: 20px;\"亲爱的用户：<br> 您好！<br> 您于");
			String now = DateUtil.getDate(null);
			emailbuffer.append(now + "申请重置公共服务平台账号密码" + userName + "<br>");
			emailbuffer.append("验证码为：</p>");
			emailbuffer.append("<p style=\"line-height: 28px; margin-top: 30px;\">" + vcode + "</p>");
			emailbuffer.append("<p style=\"line-height: 25px; font-size: 14px; margin-top: 20px;\">");
			emailbuffer.append("1.为了保障您账号的安全性，请在10分钟内完成密码重置,10分钟后失效！<br>");
			emailbuffer.append("2.本邮件由中关村公共服务平台官网系统自动发出，请勿直接回复！<br>");
			emailbuffer.append(
					"3.如果您有任何疑问或建议，请随时拨打中关村公共服务平台客服热线：400-888-1111</p></p></td></tr>\t</tbody></table><br><br>");
			String theme = "您申请重置公共服务平台账号密码的验证码";
			flag = MailSendUtil.sendMail(userName, theme, emailbuffer.toString());
		}
		if (flag) {
			userCacheImpl.setVCode(3, userName, cacheCode);
		}
		Code c = userCacheImpl.getVCode(3, userName);
		logger.info("vcode is : " + c);

		return user;
	}

	@Override
	public UserBean confirmFindPwdCode(String account, String vcode) {

		Code code = userCacheImpl.getVCode(3, account);// 1 绑定手机号，2 更新手机号,3 找回密码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}
		logger.info("account is:" + account + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}
		UserBean user = new UserBean();
		if (StringUtil.isMobileNO(account)) {// 手机发送短信验证码
			user.setPhone(account);
		} else if (StringUtil.isEmail(account)) {
			user.setEmail(account);
		}
		return user;
	}

	@Override
	public boolean resetPwd(String account, String vcode, String pwd, String confirmPwd) {

		Code code = userCacheImpl.getVCode(3, account);// 1 绑定手机号，2 更新手机号,3 找回密码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}
		logger.info("account is:" + account + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}

		UserBean user = null;
		if (StringUtil.isMobileNO(account)) {// 手机
			user = userImpl.selectOneByPhone(account);
		} else if (StringUtil.isEmail(account)) {// 邮箱
			user = userImpl.selectOneByEmail(account);
		}
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		String oldpwd = user.getPassword();
		if (!pwd.equals(confirmPwd)) {
			throw new ServiceException("user_password_is_not_same");
		}
		user.setPassword(MD5Util.sha256Hex(pwd));

		boolean flag = userImpl.updatePwd(user) > 0;
		if (flag) {
			UserUpdateLogBean updateLog = new UserUpdateLogBean();
			updateLog.setUid(user.getUid());
			updateLog.setOldData("密码：" + oldpwd);
			updateLog.setOstate(1);
			flag = userImpl.insertUpdateLog(updateLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return flag;
	}

	@Override
	public boolean checkUserPhone(String phone, String vcode) {
		Code code = userCacheImpl.getVCode(2, phone);// 根据类型获取更新手机号是验证码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}

		logger.info("phone is:" + phone + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}
		return true;
	}

	@Override
	public UserBean updatePhone(String userId, String phone, String vcode) {
		Code code = userCacheImpl.getVCode(4, phone);// 根据类型获取更新手机号是验证码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}

		logger.info("phone is:" + phone + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}

		// 更新用户手机号
		UserBean user = userImpl.selectOne(userId);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		String oldPhone = user.getPhone();
		user.setPhone(phone);
		boolean flag = userImpl.updateUser(user) > 0;
		if (flag) {
			UserUpdateLogBean updateLog = new UserUpdateLogBean();
			updateLog.setUid(user.getUid());
			updateLog.setOldData("手机号：" + oldPhone);
			updateLog.setOstate(1);
			flag = userImpl.insertUpdateLog(updateLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return user;
	}

	@Override
	public boolean sendEmailVcode(String email, int type) {
		String vcode = RandomUtil.getRandomNum(4);
		Code cacheCode = new Code();
		cacheCode.setCode(vcode);
		cacheCode.setTime(System.currentTimeMillis() / 1000);
		StringBuffer emailbuffer = new StringBuffer();
		emailbuffer.append(
				"<table style='border-collapse: collapse; border-spacing: 0; font: 18px/34px 'Microsoft Yahei', Tahoma; text-align: left;'>");
		emailbuffer.append(
				"<thead>\t\t\t<tr style='border-bottom: 1px solid #ccc;'>\t\t\t\t<th style='padding: 10px 40px;' align='left'>");
		emailbuffer.append(
				"<img src=\"http://47.93.144.246/psp-web/img/logo-oneplus.png\" alt=\"公共服务平台\"></th></tr></thead>\t");
		emailbuffer.append(
				"<tbody><tr><td style=\"padding: 0 40px;\"><p style=\"margin-top: 20px;\"亲爱的用户：<br> 您好！<br> 您于");
		String now = DateUtil.getDate(null);
		String title = null;
		if (type == 2) {
			title = "确认个人邮箱：";
		} else if (type == 4) {
			title = "申请修改个人绑定邮箱：";
		}
		emailbuffer.append(now + title + email + "<br>");
		emailbuffer.append("验证码为：</p>");
		emailbuffer.append("<p style=\"line-height: 28px; margin-top: 30px;\">" + vcode + "</p>");
		emailbuffer.append("<p style=\"line-height: 25px; font-size: 14px; margin-top: 20px;\">");
		emailbuffer.append("1.为了保障您账号的安全性，请在10分钟内完成密码重置,10分钟后失效！<br>");
		emailbuffer.append("2.本邮件由中关村公共服务平台官网系统自动发出，请勿直接回复！<br>");
		emailbuffer.append("3.如果您有任何疑问或建议，请随时拨打中关村公共服务平台客服热线：400-888-1111</p></p></td></tr>\t</tbody></table><br><br>");
		String theme = "您申请重置公共服务平台账号密码的验证码";
		boolean flag = MailSendUtil.sendMail(email, theme, emailbuffer.toString());
		if (flag) {
			userCacheImpl.setVCode(type, email, cacheCode);
		}
		return flag;
	}

	@Override
	public boolean checkUserEmail(String email, String vcode) {
		Code code = userCacheImpl.getVCode(2, email);// 根据类型获取确认邮箱验证码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}

		logger.info("email is:" + email + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}
		return true;
	}

	@Override
	public UserBean updateEmail(String userId, String email, String vcode) {
		Code code = userCacheImpl.getVCode(4, email);// 根据类型获取更新手机号是验证码
		if (code == null) {
			throw new ServiceException("vcode_is_expire");
		}

		logger.info("email is:" + email + ", vcode is:" + vcode + ", code = " + code);
		if (!vcode.equals(code.getCode())) {
			throw new ServiceException("vcode_is_error");
		}

		// 更新用户手机号
		UserBean user = userImpl.selectOne(userId);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		String oldEmail = user.getEmail();
		user.setEmail(oldEmail);
		boolean flag = userImpl.updateUser(user) > 0;
		if (flag) {
			UserUpdateLogBean updateLog = new UserUpdateLogBean();
			updateLog.setUid(user.getUid());
			updateLog.setOldData("邮箱：" + oldEmail);
			updateLog.setOstate(1);
			flag = userImpl.insertUpdateLog(updateLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return user;
	}

	@Override
	public boolean resetPassword(String userId, String oldPwd, String password, String confirmPwd) {
		// 更新用户密码
		UserBean user = userImpl.selectOne(userId);
		if (user == null) {
			throw new ServiceException("object_is_not_exist", new Object[] { "用户" });
		}
		String old = MD5Util.sha256Hex(oldPwd);
		if (!old.equals(user.getPassword())) {
			throw new ServiceException("param_is_error", "输入密码");
		}

		if (!password.equals(confirmPwd)) {
			throw new ServiceException("user_password_is_not_same");
		}

		if (password.equals(oldPwd)) {
			throw new ServiceException("user_password_can_not_same");
		}

		user.setPassword(MD5Util.sha256Hex(password));
		boolean flag = userImpl.updatePwd(user) > 0;
		if (flag) {
			UserUpdateLogBean updateLog = new UserUpdateLogBean();
			updateLog.setUid(user.getUid());
			updateLog.setOldData("密码：" + old);
			updateLog.setOstate(1);
			flag = userImpl.insertUpdateLog(updateLog) > 0;
			if (!flag) {
				throw new ServiceException("fail");
			}
		}
		return flag;

	}


}
